package demo

import (
	"context"
	"time"

	"gitee.com/851537/gmodel"
	"gitee.com/851537/gmodel/rds"
	"github.com/cloudwego/hertz/pkg/common/hlog"
)

// PubSubDemo Redis发布订阅演示
func PubSubDemo() {
	// 创建Redis客户端
	client := rds.ClientIns()

	// 创建发布订阅基类
	pubSub := gmodel.NewBaseRedisPubSub().WithClient(client)

	// 创建上下文
	ctx := context.Background()

	// 演示基本发布订阅
	demoBasicPubSub(ctx, pubSub)

	// 等待消息处理完成
	time.Sleep(2 * time.Second)

	// 关闭发布订阅
	pubSub.Close()
}

// demoBasicPubSub 基本发布订阅演示
func demoBasicPubSub(ctx context.Context, pubSub *gmodel.BaseRedisPubSub) {
	hlog.Info("=== 基本发布订阅演示 ===")

	channel := "basic_channel"

	// 订阅频道
	err := pubSub.Subscribe(ctx, channel, func(ctx context.Context, msg *rds.Message) error {
		hlog.Infof("收到基本消息: %s", msg.Payload)
		return nil
	})
	if err != nil {
		hlog.Errorf("订阅失败: %v", err)
		return
	}

	// 发布消息
	err = pubSub.Publish(ctx, channel, "Hello, Redis PubSub!")
	if err != nil {
		hlog.Errorf("发布失败: %v", err)
		return
	}

	hlog.Info("基本发布订阅演示完成")
}
